<?php

namespace app\api\controller;

use app\admin\model\Book;
use app\admin\model\Collection;
use app\admin\model\Feedback;
use app\admin\model\Free;
use app\admin\model\Invite;
use app\admin\model\MobileCode;
use app\admin\model\Rcoupon;
use app\admin\model\Registers;
use app\common\controller\Api;
use fast\Http;
use think\db\Query;
use think\Validate;
use think\Db;
use think\db\Expression;

/**
 * 个人中心接口
 */
class User extends Api
{
    //无需登录，*表都不需要
//    protected $noNeedLogin = ['login', 'mobilelogin'];
    protected  $noNeedLogin = ['login'];
    protected $noNeedRight = '*';
    protected $uid = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->uid = $this->auth->getUserId();
    }

    /**
     * @ApiTitle    (小程序登录)
     * @ApiSummary  (小程序登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiParams   (name="nickname", type="string", required=true, description="小程序昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="小程序头像")
     * @ApiReturn({
        "code": 1,
        "msg": "登录成功",
        "time": "1553839125",
        "data": {
        "token": "677afb39-1a4f-4492-84d3-0bcf32016b8a",//token
        "user_id": 27,//用户id
        "createtime": 1553839125,//登录时间
        "expiretime": 1556431125,//token失效时间
        "expires_in": 2592000//token失效剩余时间（单位s）
        "openid": 1485212522522//openid
    })
     */
    public function login(){
        if($this->request->isPost()){
            //小程序配置
            $config =  config('verify.raw');
            //小程序传递数据，包含昵称，头像，code
            $raw_data = $this->request->post();
            //验证表数据
            $rule = config('verify.user');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($raw_data)) {
                $this->error($validate->getError());
            }
            $params = [
                'appid'      => $config['app_id'],
                'secret'     => $config['secret'],
                'js_code'    => $raw_data['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            if ($result['ret']) {
                $json = (array)json_decode($result['msg'], true);
                if (isset($json['openid'])) {
                    $result = [
                        'openid' => $json['openid'],
                        'nickname' => $raw_data['nickname'],
                        'avatar' => $raw_data['avatar']
                    ];
                    $ret = $this->auth->login($result);
                    if ($ret) {
                        $data = $this->auth->getUserinfo();
                        $this->success('登录成功', ['token'=>$data['token']]);
                    }else {
                        $this->error($this->auth->getError());
                    }
                } else {
                    $this->error("登录失败",$json);
                }
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (获取个人信息)
     * @ApiSummary  (获取个人信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/info)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578640762",
        "data": {
            "id": 1,//用户uid
            "openid": "o8yED0ULOJ83BK1Lw1_hoY4ZRHeU",//openid
            "nickname": "风起时🤔  🎄",
            "avatar": "",//头像
            "token": "f7f8c6bf-b467-4e83-881a-5c427321af84",
            "user_id": 1,
            "createtime": 1578640452,
            "expiretime": 1581232452,
            "expires_in": 2591689,
            "is_vip": 1//是否为vip（0：否，1：是）
        }
    })
     */
    public function info(){
        if($this->request->isGet()){
            $res = $this->auth->getUserinfo();
            $res['nickname'] = $this->auth->emoji_decode($res['nickname']);
            //查询是否为VIP
            $res['is_vip'] = 0;
            if($res){
                //查询登录用户是否为非vip
                $res3 = Common::findWhereData('registers',['uid'=>$res['id'],'status'=>1],'id');
                if($res3){
                    $res['is_vip'] = 1;
                }
            }
            $this->success('成功',$res);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (免费预约)
     * @ApiSummary  (免费预约)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/freeBook)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="user_name", type="string", required=true, description="姓名")
     * @ApiParams   (name="mobile", type="number", required=true, description="手机号")
     * @ApiParams   (name="province", type="string", required=true, description="省")
     * @ApiParams   (name="city", type="string", required=true, description="市")
     * @ApiParams   (name="district", type="string", required=true, description="区")
     * @ApiParams   (name="address", type="string", required=true, description="详细地址")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function freeBook(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //验证表数据
            $rule = config('verify.free_book');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $freeModel = new Free();
            $data['uid'] = $this->uid;
            $res = $freeModel->create($data);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (会员注册)
     * @ApiSummary  (会员注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/userRegister)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="user_name", type="string", required=true, description="姓名")
     * @ApiParams   (name="mobile", type="number", required=true, description="手机号")
     * @ApiParams   (name="province", type="string", required=true, description="省")
     * @ApiParams   (name="city", type="string", required=true, description="市")
     * @ApiParams   (name="district", type="string", required=true, description="区")
     * @ApiParams   (name="mobile_code", type="inter", required=true, description="短信验证码")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function userRegister(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //验证表数据
            $rule = config('verify.user_register');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            //检测短信验证码是否正确
            $res2 = Common::validateMobileCode($data);
            if(!$res2){
                $this->error('验证码有误');
            }

            $registersModel = new Registers();
            $data['uid'] = $this->uid;
            //查询是否注册
            $res1 = Common::findWhereData('registers',['uid'=>$this->uid,'status'=>['in',[0,1]]],'id');
            if($res1){
                $this->error('你已经注册过');
            }
            unset($data['mobile_code']);
            $res = $registersModel->create($data);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (发送验证码)
     * @ApiSummary  (发送验证码)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/sendMobileCode)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="mobile", type="number", required=true, description="手机号")
     * @ApiReturn({
        "code": 1,
        "msg": "验证码发送成功，请注意查收！",
        "time": "1578647185",
        "data": {
            "mobile_code": 189044//短信验证码
        }
    })
     */
    public function sendMobileCode(){
        if($this->request->isPost()){
            $mobile = $this->request->post('mobile');
            $mobileCodeModel = new MobileCode();
            $search = '/^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/';
            if (!preg_match($search,$mobile)) {
                $this->error('手机号格式有误');
            }
            $mobile_code = rand(100000, 999999);
            $content = "【润保家】您的验证码为".$mobile_code."，如非本人操作请忽略本短信！";
            $info = $mobileCodeModel->where(['mobile' => $mobile, 'create_date' => date('Y-m-d')])->find();
            $where['mobile'] = $mobile;
            $where['mobile_code'] = $mobile_code;
            $where['is_use'] = 0;
            $where['expire_time'] = time()+600;
            if($info){
                if(time() < $info['create_time']+60 && $info['is_use'] == 0){
                    $this->error('不能频繁发送验证码');
                }
                if($info['count'] > 10){
                    $this->error('今天发送验证码的次数已达到了上限');
                }
                $where['count'] = $info['count'] + 1;
                $res = $mobileCodeModel->where('id',$info['id'])->data($where)->update();
            }else{
                $where['count'] = 1;
                $where['create_time'] = time();
                $where['create_date'] = date('Y-m-d');
                $res = $mobileCodeModel->insert($where);
            }
            if($res) {
                //发送验证码
                $is_ok = substr(Common::sendCode($mobile, $content),0,1);
                if($is_ok == 1){
                    $this->success('验证码发送成功，请注意查收！',['mobile_code'=>$mobile_code]);
                }else{
                    $this->error('验证码发送失败');
                }
            }
        }else{
            $this->error('请求方式错误！');
        }
    }

    /**
     * @ApiTitle    (VIP一键预约)
     * @ApiSummary  (VIP一键预约)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/book)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function book(){
        if($this->request->isPost()){
            $bookModel = new Book();
            //查询是不是vip
            $data = Common::findWhereData('registers',['uid'=>$this->uid,'status'=>1],'id,user_name,mobile,province,city,district');
            if(!$data){
                $this->error('您还不是VIP，无法一键预约');
            }

            $data['uid'] = $this->uid;
            //详细地址
            $res1 = Common::findWhereData('order',['r_id'=>$data['id']],'id,address');
            if($res1){
                $data['address'] = $res1['address'];
            }
            unset($data['id']);
            $res = $bookModel->create($data);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (分享（通过分享链接，填写免费预约体验表单，提交成功调用）)
     * @ApiSummary  (分享（通过分享链接，填写免费预约体验表单，提交成功调用）)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/share)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="share_uid", type="inter", required=true, description="分享人uid")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function share(){
        if($this->request->isPost()){
            $share_uid = $this->request->post('share_uid');
            //验证表数据
            $rule = config('verify.share');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['share_uid'=>$share_uid])) {
                $this->error($validate->getError());
            }

            if($share_uid == $this->uid){
                $this->error('不能分享自己');
            }

            //查询是否已经分享过
            $res1 = Common::findWhereData('invite',['share_uid'=>$share_uid,'uid'=>$this->uid],'id');
            if($res1){
                $this->error('不能重复分享');
            }
            //查询是否已经是下线
            $res2 = Common::findWhereData('invite',['share_uid'=>$this->uid,'uid'=>$share_uid],'id');
            if($res2){
                $this->error('不能相互分享');
            }
            //查询登录用户是否为非vip
            $res3 = Common::findWhereData('registers',['uid'=>$this->uid,'status'=>1],'id');
            if($res3){
                $this->error('您已经是VIP用户了');
            }

            $inviteModel = new Invite();
            $res = $inviteModel->create(['share_uid'=>$share_uid,'uid'=>$this->uid]);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (我的套餐)
     * @ApiSummary  (我的套餐)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/myOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="page", type="inter", required=true, description="分页页码")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578642873",
        "data": {
            "user": {//用户信息
                "id": 1,
                "user_name": "景龙",//姓名
                "mobile": "13752011725",//电话
                "province": "天津市",//省
                "city": "天津市",//市
                "district": "西青区",//区
                "address": "天津市南开区"//详细地址
                "mark": //备注
            },
            "data": [
                {
                    "id": 5,//套餐id
                    "order_sn": "order005",//套餐订单编号
                    "content": "服务内容5",//购买服务内容
                    "total_num": 10//购买次数
                },
            ],
            "total_page": 1//总页码
        }
    })
     */
    public function myOrder(){
        if($this->request->isGet()){
            $page = $this->request->get('page');
            //验证表数据
            $rule = config('verify.page');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['page'=>$page])) {
                $this->error($validate->getError());
            }
            $arr = [];
            //查询会员注册表
            $res1 = Common::findWhereData('registers',['uid'=>$this->uid,'status'=>1],'id,user_name,mobile,province,city,district');
            $r_id = '';
            $arr['user'] = '';
            if($res1){
                $r_id = $res1['id'];
                $arr['user'] = $res1;
                //查询订单最后一个地址
                $res2 = Common::findWhereData('order',['r_id'=>$r_id],'id,address,mark');
                $arr['user']['address'] = $res2['address']??'';
                $arr['user']['mark'] = $res2['mark']??'';
            }
            $res = Common::selectWherePageData('order',['r_id'=>$r_id],$page,'id,order_sn,content,total_num');
            $arr['data'] = $res;
            $total_page = Common::totalPage('order',['r_id'=>$r_id]);
            $arr['total_page'] = $total_page;
            $this->success('成功',$arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (我的服务)
     * @ApiSummary  (我的服务)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/myService)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="page", type="inter", required=true, description="分页页码")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578643476",
        "data": {
            "data": [
                {
                    "id": 4,//服务订单id
                    "order_sn": "servce_004",//服务订单编号
                    "service_content": "除螨项目",//服务项目
                    "service_name": "景龙1",//服务人员
                    "assess": "D",//服务评价
                    "mark": "备注",//备注（如果为空，则不显示该列）
                    "service_time": "2020-01-05 13:15:51"//服务时间
                },
                {
                    "id": 3,
                    "order_sn": "servce_003",
                    "service_content": "除螨项目",
                    "service_name": "景龙1",
                    "assess": "C",
                    "mark": "备注",
                    "service_time": "2020-01-05 03:15:51"
                },
            ],
            "total_page": 1//总页码
        }
    })
     */
    public function myService(){
        if($this->request->isGet()){
            $page = $this->request->get('page');
            //验证表数据
            $rule = config('verify.page');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['page'=>$page])) {
                $this->error($validate->getError());
            }
            $arr = [];
            //查询会员注册表
            $res1 = Common::findWhereData('registers',['uid'=>$this->uid,'status'=>1],'id');
            $r_id = '';
            if($res1){
                $r_id = $res1['id'];
            }
            $res = Common::selectWherePageData('service_order',['r_id'=>$r_id],$page,'id,order_sn,service_content,service_name,assess,mark,service_time');
            foreach ($res as &$value){
                $value['service_time'] = date('Y-m-d H:i:s',$value['service_time']);
            }
            $arr['data'] = $res;
            $total_page = Common::totalPage('service_order',['r_id'=>$r_id]);
            $arr['total_page'] = $total_page;
            $this->success('成功',$arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (意见反馈)
     * @ApiSummary  (意见反馈)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/feedBack)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="content", type="string", required=true, description="反馈内容")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function feedBack(){
        if($this->request->isPost()){
            $content = $this->request->post('content');
            //验证表数据
            $rule = config('verify.feed_back');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check(['content'=>$content])) {
                $this->error($validate->getError());
            }

            $feedbackModel = new Feedback();
            $res = $feedbackModel->create(['content'=>$content,'uid'=>$this->uid]);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }
}
